package com.haier.controller.ihaier;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.haier.service.IhaierService;
import com.haier.utils.EmptyUtils;
import com.haier.vo.ResponseVo;

@RestController
@RequestMapping(value = "/hipassjava/ihaier")
public class IhaierContoller {
	private static final Logger logger = LoggerFactory.getLogger(IhaierContoller.class);
	@Autowired
	private IhaierService ihaierService;

	/**
	 * 登录
	 */
	@RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
	public Object getUserInfo(@RequestBody JSONObject params) {
		try {
			String jobNumber = params.getString("jobNumber");
			if (EmptyUtils.isEmpty(jobNumber)) {
				return ResponseVo.checkError("工号不能为空");
			}
			JSONObject ihaierInfo = ihaierService.getUserInfo(jobNumber);
			return ResponseVo.success(ihaierInfo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResponseVo.error();
		}
	}

	/**
	 * 获取头像
	 */
	@RequestMapping(value = "/getFace", method = RequestMethod.GET)
	public void getFace(String jobNumber, HttpServletResponse response) {
		try {
			response.setContentType("image/jpeg");
			response.setDateHeader("expries", -1);
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Pragma", "no-cache");
			String base64Str = ihaierService.getFace(jobNumber);
			base64Str = base64Str.replace("data:image/jpeg;base64,", "");
			byte[] data = Base64.decodeBase64(base64Str.getBytes("UTF-8"));
			ServletOutputStream out = response.getOutputStream();
			out.write(data);
//			response.getWriter().write(base64Str);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 获取审批人
	 */
	@RequestMapping(value = "/getApproverId", method = RequestMethod.POST)
	public Object getApproverId(@RequestBody JSONObject params) {
		try {
			String jobNumber = params.getString("jobNumber");
			if (EmptyUtils.isEmpty(jobNumber)) {
				return ResponseVo.checkError("工号不能为空");
			}
			Integer type = params.getInteger("type");
			if (EmptyUtils.isEmpty(type)) {
				return ResponseVo.checkError("类型不能为空");
			}
			return ihaierService.getApproverId(jobNumber, type);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResponseVo.error();
		}
	}
}
